/**
 * Created by fangshufeng on 2017/11/21.
 */

import React from 'react'
import {Menu, Icon, Row, Col, List, Button} from 'antd';
import MockJson from './MockJson';
import  MockAddDevelopAlert from  './MockAddDevelopAlert'
import {MockGET, MockPOST, BaseDominAndPort, BasePath} from './MockRequest';
import {ErrorModal, ShowConfirmModal, InfoModal, CommonModal} from './MockManageModal'
import {MockDataFilter} from './MockDataFilter'
import MockAddBusiAlert from  './MockAddBusiAlert'

import 'whatwg-fetch';

const SubMenu = Menu.SubMenu;

class MockHomeRightList extends React.Component {

    render() {
        return (
            <div>
                <Row type='flex' justify='center'>
                    <Button type="primary"
                            onClick={() => {
                                this.props.addData()
                            }}>添加数据</Button>
                </Row>

                <Row type='flex' justify='start'>
                    <List
                        itemLayout="horizontal"
                        dataSource={this.props.listData}
                        renderItem={(item, index) => (
                            <List.Item>
                                <List.Item.Meta
                                    title={<div>
                                        <Row type='flex' justify='start'>
                                            <Col span={3}>
                                                <Button onClick={() => {
                                                    this.props.itemDidClick(item, index)
                                                }}> {item.name}</Button>
                                            </Col>
                                            <Col span={3} offset={18}>
                                                <Button type='danger' onClick={() => {
                                                    this.props.itemDelete(item, index)
                                                }}>删除</Button>
                                            </Col>

                                        </Row>
                                    </div>}
                                    description={BaseDominAndPort + BasePath + '/' + item.id + '/' + item.path}
                                />
                            </List.Item>
                        )}
                    />
                </Row>

            </div>
        );
    };
}

export  default class MockHome extends React.Component {

    constructor() {
        super();
        this.state = {
            busiData: {},
            listData: [],
            mockData: {},
            rowSelectIndex: -1,
            addMockData: {},
            addDevelopData: {},
            /**
             * 是否显示增加业务线的输入
             * */
            showAddBusi: false
        };
        this.relation_id = -1;
    }

    layoutDev = (busiNames, groupName, beginIndex) => {
        let devs = [];
        for (let i = 0; i < busiNames.length; i++) {
            devs.push(<Menu.Item key={beginIndex + i}>{busiNames[i]['dev_name']}</Menu.Item>)
        }
        devs.push(<Menu.Item key={'mz' + groupName }>
            <Button icon="plus" type="primary">添加开发人员</Button>
        </Menu.Item>);
        return devs;
    };

    layoutBusiName = () => {
        let busiList = Object.keys(this.state.busiData);
        let TempList = [];
        for (let i = 0; i < busiList.length; i++) {
            let busiName = busiList[i];
            let nextGroupBeginIndex = (i === 0 ? 0 : this.state.busiData[busiList[i - 1]].length);
            TempList.push(
                <SubMenu key={busiName} title={<span><Icon type="appstore"/><span>{busiName}</span></span>}>
                    {this.layoutDev(this.state.busiData[busiName], busiName, nextGroupBeginIndex)}
                </SubMenu>
            )
        }
        return TempList;
    };

    /**
     * 增加左边导航控件
     * */
    addLeftNav = () => {
        if (this.firstObj().name.length === 0) {
            return null
        }
        return (
            <Menu
                onClick={(e) => {
                    let groupNames = Object.keys(this.state.busiData);
                    /**
                     * 点击了添加开发人员按钮
                     * */
                    if (groupNames.includes(e.key.slice(2))) {
                        let currentGroupName = e.key.slice(2);
                        this.setState({
                            addDevelopData: {
                                'groupName': currentGroupName
                            }
                        });
                        return;
                    }
                    let groupName = e.keyPath[1];
                    let index = groupNames.indexOf(groupName);
                    let lastGroupCounts = 0;
                    if (index === 0) {
                        lastGroupCounts = 0;
                    } else {
                        let lastGroupName = Object.keys(this.state.busiData)[index - 1];
                        lastGroupCounts = this.state.busiData[lastGroupName].length;
                    }
                    let itemIndex = e.keyPath[0];
                    let devItems = this.state.busiData[groupName];
                    let selectDevItem = devItems[itemIndex - lastGroupCounts];
                    let relation_id = selectDevItem['id'];
                    this.handleClick(relation_id)
                }}
                defaultOpenKeys={[this.firstObj().name]}
                defaultSelectedKeys={['0']}
                mode="inline">
                {this.layoutBusiName()}
            </Menu>
        )
    };

    /**
     * 增加右边mock数据列表
     * */
    addRightMockDataList = () => {
        return (
            <MockHomeRightList
                listData={this.state.listData}
                itemDidClick={(jsonData, index) => {
                    if (Object.keys(jsonData).length > 0) {
                        this.setState({
                            mockData: jsonData,
                            rowSelectIndex: index
                        })
                    }
                }
                }
                itemDelete={
                    (jsonData, index) => {
                        ShowConfirmModal({
                            title: '确定删除该数据吗?',
                            okText: 'YES',
                            cancelText: 'NO',
                            onOk: () => {
                                if (jsonData.id === undefined) {
                                    ErrorModal('提示', '该条数据不存在！')
                                    return;
                                }

                                MockPOST('deleteMockData', {"mock_id": jsonData.id})
                                    .then(response => response.json())
                                    .then(response => {

                                        if (response.flag !== '1') {
                                            ErrorModal('提示', '删除失败！');
                                            return;
                                        }
                                        CommonModal({
                                            title: '删除成功!',
                                            onOk: () => {
                                                this.state.listData.splice(index, 1);
                                                this.setState({
                                                    listData: this.state.listData,
                                                    mockData: {}
                                                })
                                            }
                                        }, 'success')

                                    })
                            },
                            onCancel() {
                            },
                        })
                    }
                }
                addData={
                    () => {
                        if (this.relation_id === -1) {
                            ErrorModal('提示', "未选择具体的开发人员");
                            return;

                        }
                        this.setState({
                            addMockData: {"relation_id": this.relation_id},
                        });

                    }
                }/>
        )
    };

    /**
     * 查看开发者的mock数据
     * */
    handleClick = (relation_id) => {
        this.relation_id = relation_id;
        MockGET("mockData", {"relation_id": relation_id})
            .then(response => response.json())
            .then(response => response.data)
            .then((response) => {

                if (response.length === 0) {
                    this.setState({
                        listData: {}
                    });
                    InfoModal({
                        title: '提示',
                        content: (<div>该开发者暂无mock数据</div>)
                    });
                    return;
                }
                this.setState({
                    listData: response
                })
            });
    };

    /**
     * 修改mock数据
     * */
    changMockData = () => {
        return (
            <Col span={24}>
                <MockJson
                    dataSource={this.state.mockData}
                    hidenAction={() => {
                        this.setState({
                            mockData: {},
                        })
                    }}
                    onOk={ (value) => {

                        if (value.name.length === 0 ||
                            value.data.length === 0 ||
                            value.path.length === 0) {
                            ErrorModal('提示', '有未填项');
                            return;
                        }

                        MockDataFilter(value.data, (e) => {

                            if (e) {
                                ErrorModal('提示', '该数据是无效的json，修改后重试');
                                return;
                            }

                            MockPOST('updateMockData', {
                                "mock_id": value.id,
                                "name": value.name,
                                "data": value.data,
                                "path": value.path
                            })
                                .then(response => response.json())
                                .then(response => {
                                    if (response.flag !== '1') {
                                        CommonModal({
                                            title: '修改失败',
                                            onOk: () => {
                                                this.setState({
                                                    addMockData: {},
                                                })
                                            }
                                        }, "error")
                                        return;

                                    }

                                    CommonModal({
                                        title: '修改成功!',
                                        onOk: () => {
                                            //更新列表的数据源
                                            let tempListData = this.state.listData;
                                            tempListData[this.state.rowSelectIndex] = value;
                                            this.setState({
                                                listData: tempListData,
                                                mockData: {},
                                            })
                                        }
                                    }, 'success')

                                });
                        });
                    }
                    }
                />
            </Col>)
    };

    /**
     * 添加新的mock数据
     * */
    addMockData = () => {
        return (
            <Col span={24}>
                <MockJson
                    dataSource={this.state.addMockData}
                    hidenAction={() => {
                        this.setState({
                            addMockData: {},
                        })
                    }}
                    onOk={
                        (value) => {

                            if (value.name.length === 0 ||
                                value.data.length === 0 ||
                                value.path.length === 0) {
                                ErrorModal('提示', '有未填项');
                                return;
                            }

                            MockDataFilter(value.data, (e) => {
                                if (e) {
                                    ErrorModal('提示', '该数据是无效的json，修改后重试');
                                    return;
                                }
                                MockPOST('addMockData', {
                                    "mock_id": value.relation_id,
                                    "name": value.name,
                                    "data": value.data,
                                    "path": value.path
                                })
                                    .then(response => response.json())
                                    .then(response => {
                                        if (response.flag === '1') {
                                            CommonModal({
                                                title: '成功!',
                                                onOk: () => {
                                                    /**
                                                     *     //更新列表的数据源
                                                     let tempListData = this.state.listData;
                                                     tempListData.unshift(value);
                                                     this.setState({
                                                        listData: tempListData,
                                                        addMockData: {}
                                                         })
                                                     * */
                                                    this.setState({
                                                        addMockData: {}
                                                    })
                                                    this.handleClick(value.relation_id)
                                                }
                                            }, 'success')

                                        } else {
                                            CommonModal({
                                                title: '提示',
                                                onOk: () => {
                                                    this.setState({
                                                        addMockData: {},
                                                    })
                                                }
                                            }, "error")
                                        }
                                    })
                            });
                        }
                    }
                />
            </Col>)
    };
    /**
     * 添加新的开发人员
     * */
    addDeveloper = () => {
        return (
            <Col span={24}>
                <MockAddDevelopAlert
                    dataSource={this.state.addDevelopData}
                    hidenAction={() => {
                        this.setState({
                            addDevelopData: {},
                        })
                    }}
                    okAction={(value) => {

                        if (value.developName.length === 0) {
                            ErrorModal("提示", '开发人员不能为空')
                            return;
                        }

                        MockPOST('addDevelop', {
                            'businessName': value.groupName,
                            'developName': value.developName
                        })
                            .then(response => response.json())
                            .then(response => {
                                if (response.flag !== '1') {
                                    ErrorModal('提示', response.msg)
                                    return;

                                }
                                CommonModal({
                                    title: '添加成功',
                                    onOk: () => {
                                        this.setState({
                                            addDevelopData: {},
                                        });
                                        this.fecthBusiAndDev()
                                    }
                                }, 'success')

                            })
                    }}
                />
            </Col>
        )
    };

    /**
     * 增加业务线
     * */
    addBusi = () => {
        return (
            <Col span={24}>
                <MockAddBusiAlert
                    showAddBusi={this.state.showAddBusi}
                    hidenAction={() => {
                        this.setState({
                            showAddBusi: false,
                        })
                    }}
                    okAction={
                        (busiName) => {
                            if (busiName.length === 0) {
                                ErrorModal("提示", "业务线名称不能为空");
                                return;
                            }
                            MockPOST("addBusiness", {
                                "businessName": busiName
                            })
                                .then(response => response.json())
                                .then(response => {
                                    if (response.flag !== '1') {
                                        ErrorModal("提示", response.msg);
                                        return;
                                    }

                                    CommonModal({
                                        title: '成功！',
                                        onOk: () => {
                                            this.setState({
                                                showAddBusi: false,
                                            })
                                            this.fecthBusiAndDev();
                                        }
                                    }, "success");
                                })
                        }
                    }
                />
            </Col>)

    };

    render() {
        return (
            <Row >
                <Col span={1} style={{backgroundColor: 'red'}}/>
                <Col span={22}>
                    <Col span={3}>
                        <Row>
                            {this.addLeftNav()}
                        </Row>
                        <Row type='flex' justify='center' style={{marginTop: 80}}>
                            <Button type="danger"
                                    icon="plus-circle"
                                    size='large'
                                    onClick={() => {
                                        this.setState({
                                            showAddBusi: true
                                        })
                                    }}
                            >添加业务线</Button>
                        </Row>
                    </Col>

                    <Col span={16} offset={1}>
                        {this.addRightMockDataList()}
                    </Col>
                </Col>

                <Col span={1} style={{backgroundColor: 'red'}}/>
                {this.changMockData()}
                {this.addMockData()}
                {this.addDeveloper()}
                {this.addBusi()}
            </Row>
        );
    }

    componentDidMount() {
        this.fecthBusiAndDev()
    }

    /**
     * 获取业务线和开发人员列表
     * */
    fecthBusiAndDev = () => {
        MockGET('businessListAndDev')
            .then(response => response.json())
            .then(response => response.data)
            .then((dataDic) => {
                this.setState({
                    busiData: dataDic,
                });
                this.handleClick(this.firstObj().relation_id)

            });
    };

    firstObj = () => {
        let firstGroupName = Object.keys(this.state.busiData)[0];
        let relation_id = -1;
        if (firstGroupName === undefined) {
            firstGroupName = '';
        } else {
            let devItems = this.state.busiData[firstGroupName];
            let selectDevItem = devItems.length > 0 ? devItems[0] : 0;
            relation_id = selectDevItem['id'];
        }

        return {
            'name': firstGroupName,
            'itemIndex': 0,
            'relation_id': relation_id
        }
    }
}
